package com.dongbo.recorder.screenrecord.utils;

import static com.dongbo.recorder.screenrecord.Constants.ANDROID_ID;

import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import com.dongbo.recorder.screenrecord.AppLpds;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * author:lutengxuan
 * date:2023/7/4
 * describe:通用工具类
 */
public class Utils {
    /**
     * 设备id  facilityId
     */
    public static String getUniqueID(Context context) {
        String id = AppLpds.getMySp().getString(ANDROID_ID, "");
        if (TextUtils.isEmpty(id)) {
            final String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            if (!TextUtils.isEmpty(androidId) && !"9774d56d682e549c".equals(androidId)) {
                try {
                    UUID uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                    id = uuid.toString();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            if (TextUtils.isEmpty(id)) {
                id = getUUID();
            }
            id = TextUtils.isEmpty(id) ? UUID.randomUUID().toString() : id;
            AppLpds.getMySp().putString(ANDROID_ID, id);
        }
        return id;
    }

    private static String getUUID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                serial = Build.getSerial();
            } else {
                serial = Build.SERIAL;
            }
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            serial = "serial"; // 随便一个初始化
        }

        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

}
